using System.Threading;
using Config;
using Cysharp.Threading.Tasks;
using Entity;
using MoonFramework.Buff;
using MoonFramework.Scripts.Tool.System.Setting;
using MoonFramework.Template;
using Tool;
using Tool.Name;
using UnityEngine;

namespace Map.MapObject.HitObject
{
    public abstract class BaseHitMapObject : BaseMapObject
    { 
        [HideInInspector] public float hp;
        public AudioClip[] hurtAudioClips;
        public float MaxHp;
        private CancellationTokenSource _token;
        protected WeaponType _weaponType;
        [SerializeField] private int lootConfigID = -1;

        public override void Init(BaseMapBlock mapBlock, ulong id)
        {
            base.Init(mapBlock, id);
            _token = new();
            hp = MaxHp;
        }

        public override bool DoHit(Actor actor, float dir)
        {
            if (actor is not Character player) return true;
            return !player.buffFsm.CheckBuff(nameof(DisarmBuff)) &&
                   player.WeaponController.CurrentWeapon.WeaponData != null &&
                   ((ItemWeaponInfo)player.WeaponController.CurrentWeapon.WeaponData.Config.ItemTypeInfo).WeaponType == _weaponType;
        }
        
        protected async UniTaskVoid RotationTransform(float f)
        {
            Quaternion targetRotation1 = Quaternion.Euler(f, 0, f);
            Quaternion targetRotation2 = Quaternion.Euler(0, 0, 0);

            for (int i = 0; i < 5; i++)
            {
                await UniTask.Yield(_token.Token); 
                transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation1, 0.2f); // 0.2f 是插值的平滑系数
            }

            for (int i = 0; i < 5; i++)
            {
                await UniTask.Yield(_token.Token);
                transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation2, 0.2f); // 0.2f 是插值的平滑系数
            }
        }
        
        protected override void Dead()
        {
            _token.Cancel();
            _token.Dispose();
            RemoveOnMap();
            LootObject();
        }

        private void LootObject()
        {
            if(lootConfigID == -1) return; //没有掉落物
            LootConfig lootConfig = ConfigManager.Instance.GetConfig<LootConfig>(ConfigName.Loot, lootConfigID);
            if(!lootConfig) return;
            lootConfig.GetMapObject(_mapBlock, transform.position + Vector3.up);
        }
    }
}